﻿using B.S.BaseData.Api.Write.Applicantion.Command.RBAC;
using B.S.BaseData.Api.Write.GetCelim;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.RBAC;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.RBAC
{
    public class UserUpdateCommandHandler : IRequestHandler<UserUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> _userModel;
        private readonly IBaseRepository<UserRoleModel> _userroleModel;
        private readonly IIdContextCemil _idContextCemil;
        public UserUpdateCommandHandler(IBaseRepository<UserModel> userModel, IBaseRepository<UserRoleModel> userroleModel, IIdContextCemil idContextCemil)
        {
            _userModel = userModel;
            _userroleModel = userroleModel;
            _idContextCemil = idContextCemil;
        }
        public async Task<APIResult<int>> Handle(UserUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            var list = await _userModel.GetValues(x=>x.Id==request.Id);
            list.UserName=request.UserName;
            list.UserPwd=request.UserPwd;
            await _userModel.UpdateAsync(list);

            var res = _userroleModel.GetAll().Where(x=>x.UserId==request.Id).ToList();

            foreach (var item in res)
            {
                await _userroleModel.Delete(item);
            }

            foreach (var item in request.RoleIds)
            {
                UserRoleModel model=new UserRoleModel();
                model.Id=YitIdHelper.NextId();
                model.UserId=request.Id;
                model.RoleId = item;
                model.CreateName = _idContextCemil.UserName;
                await _userroleModel.CreateAsync(model);
            }

            result.Code = ApiEnum.Success;
            result.Msg = "用户信息修改成功";
            result.Data = 1;
            return await Task.FromResult(result);
        }
    }
}
